

var  UrbanAirshipClient = Packages.urbanairship.jaxrs.UrbanAirshipClient;
var  APS = Packages.urbanairship.APS;
var  Push = Packages.urbanairship.Push;
var  Device = Packages.urbanairship.Device;


//
//Send an alert through Urban Airship service
//
function pushAlertToAccount( account, alert, badge ) 
{
	if( account == null ) {
		CMC.log.warn( "account is null!" );
		return false;
	} 
	
	var tenant = CMC.entityManager.findSystemTenant();

	var attr = tenant.attributesToMap();

	var appKey = attr.get("airship.appkey");
	if( appKey == null ) {
		CMC.log.warn( "'airship.appkey' not found in system tenant!" );
		return false;
	}
	var masterKey = attr.get("airship.masterkey");
	if( masterKey == null ) {
		CMC.log.warn( "'airship.masterkey' not found in system tenant!" );
		return false;
	}
	
	var client = new UrbanAirshipClient(appKey, masterKey);

	var attr = account.attributesToMap();

	var deviceToken = attr.get("deviceToken");
	
	if( deviceToken == null ) {
		CMC.log.warn( "'deviceToken' not set for account " + account.id );
		return false;
	} 

	/*
	var dev = new Device();
	
	dev.setiOSDeviceToken("");
		
	client.register(dev);
	 */

	var aps = new APS();
	aps.setAlert(alert);
	if( badge!=null ) aps.setBadge(badge);

	var p = new Push();
	p.setDeviceTokens(toList([ deviceToken ]));
	p.setAps(aps);

	client.sendPushNotifications(p);
	
	return true;

}

//
// Send an alert through Urban Airship service
//
function push_alert( accountId, alert, badge  )
{
	var account = CMC.entityManager.findAccountById(accountId);

	if( account == null ) {
		Log.error( "account not found " + accountId );
		return false;
	} 

	return pushAlertToAccount(account, alert, badge);
}
